<template>
  <d2-container>
    <div class="form-area">
      <el-form
        ref="addForm"
        :model="addForm"
        label-width="140px"
        style="width: 80%; height:auto;"
      >
        <!-- 基本信息 -->
        <div class="form-title">
          <h3>基本信息</h3>
        </div>
<el-divider></el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采购原因简述：" prop="purchaseReason">
              <el-input v-model="addForm.purchaseReason" placeholder="请输入采购原因" readonly=""></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购订单编码：" prop="orderNo">
              <el-input v-model="addForm.orderNo" placeholder="采购订单编码，自动生成" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供应商名称：" prop="supplierName">
              <el-input v-model="addForm.supplierName" readonly=""></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="联系人：" prop="supplierContact">
              <el-input v-model="addForm.supplierContact" placeholder="请输入供应商联系人" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划到货日期：" prop="expectedArrivalTime">
                <el-input v-model="addForm.expectedArrivalTime" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入库状态：" prop="stockStatus">
              <el-select v-model="addForm.stockStatus" placeholder="未入库" disabled>
                <el-option label="全部" value></el-option>
                <el-option label="未入库" value="1"></el-option>
                <el-option label="部分入库" value="2"></el-option>
                <el-option label="全部入库" value="3"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="总金额：" prop="amountTotal">
              <el-input v-model="addForm.amountTotal" placeholder="总金额" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="已付金额：" prop="paidAmount">
              <el-input v-model="addForm.paidAmount" placeholder="已付金额" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="未付金额：" prop="toPayAmount">
              <el-input v-model="addForm.toPayAmount" placeholder="未付金额" :readonly="true"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="付款状态：" prop="payStatus">
              <el-select v-model="addForm.payStatus" placeholder="全部" disabled>
                <el-option label="全部" value></el-option>
                <el-option label="未付" value="0"></el-option>
                <el-option label="部分付款" value="1"></el-option>
                <el-option label="已付款" value="2"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
                <el-col :span="24">
                    <el-form-item label="附件/便笺：">
                        <el-upload
                        action=""
                        class="upload-demo"
                        :file-list="fileList"
                        list-type="text"
                        :show-file-list="true"
                        :disabled="true"
                        >
                        <el-link target="_blank" :href="downloadUrl" :underline="false">
                            <el-button v-if="showFileList()" style="margin-left: 10px;" size="small" type="success" >下载附件</el-button>
                        </el-link>
                        </el-upload>
                    </el-form-item>
                </el-col>
            </el-row>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="商品备注" prop="remark">
              <el-input type="textarea" v-model="addForm.remark" :readonly="isDetails"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="form-title">
          <h3>审核信息</h3>
        </div>
        <el-divider></el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="提交人" prop="submitor">
              <el-input type="text" v-model="addForm.submitor" placeholder="提交人" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="提交时间" prop="submitTime">
              <el-date-picker
                v-model="addForm.submitTime"
                type="datetime"
                placeholder="提交时间"
                readonly
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="审核人" prop="auditor">
              <el-input type="text" v-model="addForm.auditor" placeholder="审核人" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="审核时间" prop="authTime">
              <el-date-picker
                v-model="addForm.authTime"
                type="datetime"
                placeholder="审核时间"
                readonly
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="审核状态" prop="status">
              <el-select v-model="addForm.status" placeholder="全部" disabled>
                <el-option label="全部" value></el-option>
                <el-option label="未提交" value="0"></el-option>
                <el-option label="审核中" value="1"></el-option>
                <el-option label="审核通过" value="2"></el-option>
                <el-option label="审核拒绝" value="3"></el-option>
                <el-option label="采购取消" value="4"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="审核说明" prop="authDesc">
              <el-input
                type="textarea"
                :rows="4"
                v-model="addForm.authDesc"
                placeholder="审核说明"
                readonly
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <div class="form-title">
          <h3>系统信息</h3>
        </div>
        <el-divider></el-divider>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="创建人" prop="creator">
              <el-input type="text" v-model="addForm.creator" placeholder="创建人" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="创建时间" prop="createTime">
              <el-date-picker
                v-model="addForm.createTime"
                type="datetime"
                placeholder="创建时间"
                readonly
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="修改人" prop="reviser">
              <el-input type="text" v-model="addForm.reviser" placeholder="修改人" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="修改时间" prop="reviseTime">
              <el-date-picker
                v-model="addForm.reviseTime"
                type="datetime"
                placeholder="修改时间"
                readonly
                style="width: 100%;"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        

        <div class="form-title">
          <h3>采购明细</h3>
        </div>
<el-divider></el-divider>
        <el-row :gutter="20">
          <el-col :span="24">
            <template>
              <div class="table-header">
              </div>
              <div class="form-table">
                <el-table :data="tableDetailList" stripe border style="width: 100%">
                  <el-table-column type="index" fixed label="序号" width="50"></el-table-column>
                  <el-table-column label="SPU商品" prop="productName"></el-table-column>
                  <el-table-column label="SKU商品" prop="productSkuName"></el-table-column>
                  <el-table-column label="采购数量" prop="purchaseQuantity"></el-table-column>
                  <el-table-column label="采购单位" prop="unitName"></el-table-column>
                  <el-table-column label="采购单价（元）" prop="purchasePrice"></el-table-column>
                  <el-table-column label="采购金额（元）" prop="purchaseAmount"></el-table-column>
                  <el-table-column label="折扣(%)" prop="discountRate" :formatter="formatPercent"></el-table-column>
                  <el-table-column label="折后金额（元）" prop="purchaseAmountDiscount"></el-table-column>
                  <el-table-column label="已入库数量" prop="stockInQuantity"></el-table-column>
                </el-table>
              </div>
            </template>
          </el-col>
        </el-row>

        <!-- 保存 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item>
              <div class="form-submit">
                <el-button class="form-submit-btn" :disabled="loading" type="primary" @click="doAuth()" >审核</el-button>
                <el-button class="form-cancle-btn" :disabled="loading" @click="closeCurrentPage()">关闭</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 弹框-审核表单 -->
		<template>
			<el-dialog title="采购单审核" width="50%" :visible.sync="showAuthForm" :before-close="handleCloseAuthForm">
        <el-divider></el-divider>
				<div class="form-area">
					<el-form ref="authForm" :model="authForm" :rules="rulesAuthForm" label-width="100px" style="height:auto">
						<el-row :gutter="20">
							<el-col :span="12">
								<el-form-item label="审核结果" prop="status">
									<el-radio-group v-model="authForm.status">
										<el-radio label="2" border>通过</el-radio>
										<el-radio label="3" border>不通过</el-radio>
									</el-radio-group>
								</el-form-item>
							</el-col>
						</el-row>
						<el-row :gutter="20">
							<el-col :span="12">
								<el-form-item label="审核说明" prop="authDesc">
									<el-input type="textarea" :rows="4" v-model="authForm.authDesc" placeholder="请输入审核说明"></el-input>
								</el-form-item>
							</el-col>
						</el-row>
					</el-form>
				</div>
				<div class="dialog-footer" slot="footer">
					<el-button @click="closeShowAuthForm()">取消</el-button>
					<el-button type="primary" @click="confirmAuthForm('authForm')">确定</el-button>
				</div>
			</el-dialog>
		</template>
    
  </d2-container>
</template>

<script>
import dayjs from "dayjs";
import util from "@/libs/util";
import { mapActions, mapState } from 'vuex'
import { getOrderInfo, listOrderDetail, auditOrder } from "@api/purchase/purchase";


export default {
  components: {},
  props: {
    isDetails: {
      type: Boolean,
      default: false
    },
    productDetails: Object
  },
  data() {
    return {
      supplierTree: [], //供应商下拉框
      unitList: [],     //采购单位下拉框
      
      dateSelect: "", //日期控件

      isSubmit: false,  //用于解决提交时，重新赋值unitId导致触发查询的问题

      showProductList: false,

      fileList: [],
      downloadUrl: "",

      preSupplierId: "",  //缓存切换前的供应商ID

      addForm: {
        ifSubmit: 0,    // 保存时是否提交
        id: "",
        purchaseReason: "",
        orderNo: "",
        supplierId: "",
        supplierName: "",
        supplierContact: "",
        supplierContactPhone: "",
        expectedArrivalTime: "",
        contractUrl: "",
        status: "0",
        stockStatus: "0",
        payStatus: "0",
        amountTotal: "0",
        paidAmount: "0",
        toPayAmount: "0",
        remark: "",
        submitor: "",
        submitTime: "",
        auditor: "",
        authTime: "",
        authDesc: "",
        creator: "",
        createTime: "",
        reviser: "",
        reviseTime: "",
        detailList: [] //用于提交采购明细
      },

      tableDetailList: [],

      showAuthForm: false,
      authForm: {
        orderId: '',
        status: '',
        authDesc: ''
      },
      rulesAuthForm: {
        status: [{ required: true, message: '请选择审核结果', trigger: 'blur' }],
        authDesc: [{ required: true, message: '请输入审核说明', trigger: 'blur' }, { min: 1, max: 128, message: '长度在 1 到 128 个字符', trigger: 'blur' }]
      },
      
      loading: false,
      isReturnList: false // 关闭页面是否返回列表
    };
  },
  watch: {
   
  },
  computed: {
    ...mapState('d2admin/page', ['opened', 'current'])
  },
  methods: {
    ...mapActions('d2admin/page', ['close']),


    // 关闭
    closeCurrentPage () {
      // 关闭当前窗口
	    this.isReturnList = true
      let tagName = this.current
      this.close({ tagName })
    },
    // 审核
    doAuth () {
      // 弹出审核框审核
      this.showAuthForm = true
    },
    handleCloseAuthForm (done) {
      this.authForm = {
        id: this.purchaseStockInDetailId,
        status: '',
        authDesc: ''
      }
      done()
    },
    closeShowAuthForm () {
      this.authForm = {
        orderId: this.orderId,
        status: '',
        authDesc: ''
      }
      this.showAuthForm = false
    },
    confirmAuthForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.loading = true

          auditOrder(this.authForm)
            .then(res => {
              if (res.code == '000000') {
                this.$message({ message: res.message, type: 'success' })
                this.loading = false
                this.closeShowAuthForm()
                this.closeCurrentPage()
              } else {
                this.$message({ message: res.message, type: 'error' })
              }
            })
            .catch(err => {
              console.log('err', err)
              this.loading = false
            })
        }
      })
    },


    getPurchaseOrder(orderId) {
      getOrderInfo({
          orderId: orderId
      })
          .then((res) => {

              //审核表单赋值
              this.authForm.orderId = res.data.id;
              this.authForm.status = res.data.status;
              this.authForm.authDesc = res.data.authDesc;

              this.addForm.id = res.data.id;
              this.addForm.purchaseReason = res.data.purchaseReason;
              this.addForm.orderNo = res.data.orderNo;
              this.addForm.supplierId = res.data.supplierId;
              this.addForm.supplierName = res.data.supplierName;
              this.addForm.supplierContact = res.data.supplierContact;
              this.addForm.supplierContactPhone = res.data.supplierContactPhone;
              // this.addForm.expectedArrivalTime = res.data.expectedArrivalTime;
              this.addForm.expectedArrivalTime = dayjs(res.data.expectedArrivalTime).format('YYYY-MM-DD');
              this.addForm.contractUrl = res.data.contractUrl;
              this.addForm.status = res.data.status;
              this.addForm.stockStatus = res.data.stockStatus;
              this.addForm.payStatus = res.data.payStatus;
              this.addForm.amountTotal = res.data.amountTotal;
              this.addForm.paidAmount = res.data.paidAmount;
              this.addForm.toPayAmount = res.data.toPayAmount;
              this.addForm.remark = res.data.remark;
              this.addForm.submitor = res.data.submitor;
              this.addForm.submitTime = res.data.submitTime;
              this.addForm.auditor = res.data.auditor;
              this.addForm.authTime = res.data.authTime;
              this.addForm.authDesc = res.data.authDesc;

              this.addForm.creator = res.data.creator;
              this.addForm.createTime = res.data.createTime;
              this.addForm.reviser = res.data.reviser;
              this.addForm.reviseTime = res.data.reviseTime;

              this.addForm.status = this.addForm.status.toString();
              this.addForm.payStatus = this.addForm.payStatus.toString();
              this.addForm.stockStatus = this.addForm.stockStatus.toString(); 
              // this.dateSelect = dayjs(this.addForm.expectedArrivalTime).format("YYYY-MM-DD"); 

              this.preSupplierId = res.data.supplierId;

              if(this.addForm.contractUrl != "" && this.addForm.contractUrl != undefined) {
                this.fileList.push({
                    name: res.data.contractUrl,
                    url: res.data.fullContractUrl
                })
              }
              this.downloadUrl = res.data.fullContractUrl;
          })
          .catch((err) => {
              console.log("err", err);
              this.loading = false 
          });
    },
    getPurchaseOrderDetailList(orderId) {   
      listOrderDetail({ orderId: orderId, ifNeedUnitList: 1 })
        .then(res => {
          if (res.code == "000000") {

              this.tableDetailList = res.data;

              this.$set(this.addForm,"detailList", []);      //查询主表时，会覆盖该属性，需要重新赋值

              this.loading = false;
          }
        })
        .catch(err => {
          console.log("err", err);
          this.loading = false;
        });
    },
    showFileList() {
        if(this.fileList.length > 0) {
            return true;
        } else {
            return false;
        }
    },
  
    formatPercent(row, column) {
      return row.discountRate + "%";
    },

    handleClose(done) {
      this.searchProductForm = {
        supplierId: this.addForm.supplierId,
        purchasePlanNo: "",
        productName: ""
      };
      done();
    },

    // 返回列表
    closePage() {
      this.$emit("close");
    },
    cancel () {
      // 关闭当前窗口
      let tagName = this.current
      this.close({ tagName })
    },
  },
  
  created() {

  },
  mounted() {

    this.loading = true;

    let orderId = sessionStorage.getItem('purchaseOrderId');
    
    this.getPurchaseOrder(orderId);
    this.getPurchaseOrderDetailList(orderId);

    // 上传图片插件的请求头
    let getId = util.cookies.get("client");
    let client_id;
    let getId2_reverse = getId.substring(0, 6);
    let getId2 = getId2_reverse
      .split("")
      .reverse()
      .join(""); // 后6位
    let getId1 = getId.substring(6, 13); // 前7位
    client_id = "client" + getId1 + getId2;

    let democracy = util.cookies.get("democracy");

    this.headerParams.clientId = client_id;
    this.headerParams.democracy = democracy;
  },
  
  beforeDestroy () {
    // 跳转到列表页面
    if (this.isReturnList) {
      this.$router.push('/purchase/index')
    }
    
  }
};
</script>

<style scoped>
.step {
  width: 80%;
  padding: 20px 0 40px 0;
}
.step-title {
  cursor: pointer;
}
::v-deep .image-placeholder {
  width: 50px;
  height: 50px;
  align-items: center;
  justify-content: center;
  background-color: #eee;
  display: flex;
}

::v-deep .edui-editor-iframeholder.edui-default {
  height: 300px !important;
}

#myImage {
  background-color: #6b116b;
  width: 80px;
  height: 32px;
  padding-top: 8px;
  padding-left: 8px;
  border-color: white;
}
.addMyImage {
  background-color: #b24cff;
  width: 104px;
  height: 32px;
  padding-top: 8px;
  padding-left: 12px;
  border: 0px solid white;
}
.addMyImage:hover {
  background-color: #b24cff;
}
.addNotMyImage {
  background-color: #ccc;
}
.addNotMyImage:hover {
  background-color: #ccc;
}

.table-header {
  display: flex;
}
</style>
